<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 用户管理
 * @author zxj
 *
 */
class Member extends MY_Controller {
    private $t_user = 'user';  //用户表
    private $t_userinfo = 'user_login_log';  //用户日志表
    function __construct() {
        parent::__construct();
        //加载用户模型
        $this->load->model('users_model');
        $this->load->model('api_model/tom_account_model','account_model');
        $allowUser = array('admin','prezwang','zlj','lyb','ferran','anna','Julie','david','chuyilin','邱远琴');
        if(!in_array($this->users['account'],$allowUser)){
            //js_goto('','无权限访问',1);
        }
		  $this->lang->load('member');
    }

    /**
     * 用户列表
     */
    function index()
    {
        //获取表单数据
        $data = $formField = gp();
        //默认select设置
        $optStatus[$data['status']] = 'selected';
        $data['optStatus'] = $optStatus;

        $data['rolelist'] = $this->users_model->GetRole(0);//获取所有角色列表
        /**
         * 搜索逻辑处理
         */
        $where = $whereLike = array();
        //获取表字段(即查询条件,时间查询额外处理)
        $fieldsList = $this->db->list_fields($this->t_user);
        $fieldsList[] = 'status';

        //需要模糊查询的字段
        $likeAry = array('account', 'name', 'position','email');
        //拼接查询字符串
        $searchStr = 'users/member/?';
        foreach ($formField as $key => $val) {
            if ($val==='' || !in_array($key, $fieldsList)) continue;
            if (in_array($key, $likeAry)) {
                $whereLike[$key] = $val;
            }elseif($key == 'status') {
                $where['active'] = $val;
                $where['is_open'] = $val;
            } else {
                $where[$key] = $val;
            }
            $searchStr .= $key . '=' . $val . '&';
        }
        $searchStr = rtrim($searchStr, '&');
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->users_model->countRows($this->t_user, $where, '', $whereLike);
        $config['per_page'] = 15;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $page = max(1, intval($data['page']));
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $data['show_pages'] = $this->pagination->create_links();
        $num_page = ceil($config['total_rows'] / $config['per_page']);
        $data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";
        //查询
        $datalist = $this->users_model->select($this->t_user, $slimit, $config['per_page'], 'id desc', $where, '', $whereLike);
        //重构数据
        foreach ($datalist as $key => &$vary) {
            $vary['active_as_name'] = $vary['active'] ? lang('member_gb') : lang('member_qy');
            $vary['isopen_as_name'] = $vary['is_open'] ? lang('member_gb') : lang('member_qy');
            //这里要做一个空验证，防止人为操作错的异常被抛出
            if (!empty($vary['role_id'])) {
                $vary['role'] = $this->users_model->getRolesByIds(rtrim($vary['role_id'], ','));//这里的id需要去右边逗号，sqw
            } else {
                $vary['role'] = '<span style="color:#db3652;">没有权限</span>';
            }
        }
        unset($vary);
        $joinList=$this->users_model->getJoinList();
        $data['joinList'] = $joinList;
        $data['dataList'] = $datalist;

        //视图以及样式
        $this->load->view('defaults/member_list', $data);
        $this->load->view('defaults/common/footer');
    }


    /**
     * 新增用户
     */
    function add(){
        $gp=gp();
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //插入数据
        $submits = $gp['submits'];
        if ($submits) {
            //获取表字段
            $fieldsList = $this->db->list_fields($this->t_user);
            //组织插入的数据
            $indata = array();
            //分割角色将角色名和ID都存入用户表
            $roleNameId=explode('_',$gp['roleNameId']);
            $gp['role_id']=$roleNameId[0];
            $gp['role']=$roleNameId[1];
            $gp['password']=md5($gp['password']);
            if($gp['role_id']==1 && $this->users['role_id'] != 1){
                js_goto('','数据异常',1);
                exit();
            }
            foreach ($gp as $key=>$val) {
                if(($val || $val===0) && in_array($key,$fieldsList)){
                    $indata[$key] = $val;
                }
            }
            $this->common_model->insert($this->t_user,$indata);
            js_goto(blang_url('users/member/'),'新增成功!');
        }else{
            //角色类型
            $id=1;
            //只有管理员可以添加管理员  其他角色不可以
            if($this->users['role_id'] == 1){
                $id='';
            }
            $roleList=$this->users_model->GetRole($id);
            $language=$this->uri->segment(1);
            foreach($roleList as &$row){
                switch($language){
                    case 'sc':
                        $row['name']=$row['name_ch'];
                        break;
                    case 'english':
                        $row['name']=$row['name_en'];
                        break;
                    default:
                        $row['name']=$row['name_en'];
                        break;
                }
            }
            unset($row);
            $data['roleList'] = $roleList;
            //视图以及样式
            $this->load->view('defaults/member_post',$data);
            $this->load->view('defaults/common/footer');
        }
    }

    /**
     * 新增合作客户
     */
    public function AddConsumer(){
        $gp=gp();
        if($gp['manager']) {
            $manager = explode('_', $gp['manager']);
            $gp['manager_id']=$manager[0];
            $gp['manager_name']=$manager[1];
        }else{
            $gp['manager_id']=0;
            $gp['manager_name']='';
        }
        unset($gp['manager']);
        $this->users_model->addcustomers($gp);
        redirect(blang_url('users/member/ConsumerList'));
    }

    /**
     * 删除合作客户
     * @param $id
     */
    public function DeleteConsumer($id){
        $this->users_model->deletecustomerslist($id);
        $this->ConsumerList();
    }
    /**
     * 合作客户列表
     */
    public function ConsumerList(){
        $gp=gp();
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str='?name='.$gp['keyword'].'&email='.$gp['keyword'].'&tel='.$gp['keyword'].'&type='.$gp['type'].'&manager_id='.$gp['manager_id'];
        $keyword=array();
        if($gp['keyword']) {
            $keyword = array(
                'name' => $gp['keyword'],
                'email' => $gp['keyword'],
                'tel' => $gp['keyword'],
            );
        }
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('users/member/ConsumerList'.$str);
        $config['total_rows'] = $this->users_model->CountCustomersSum($keyword,$gp['type'],$gp['manager_id']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageShow']= $this->pagination->create_links();
        $consumerList=$this->users_model->customerslist($keyword,$gp['type'],$gp['manager_id'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        foreach($consumerList as &$row){
            switch($row['type']){
                case '1':
                    $row['typeText']='电商客户';
                    break;
                case '2':
                    $row['typeText']='品牌客户';
                    break;
                case '3':
                    $row['typeText']='个人';
                    break;
                case '4':
                    $row['typeText']='维修店';
                    break;
                default:
                    $row['typeText']='无法识别';
                    break;
            }
        }
        unset($row);
        $data['consumerList']=$consumerList;
        $data['salesList']=$this->users_model->getAccount(12);
        $data['siteList']=$this->users_model->GetSite();
        $data['str']=$str;
        $data['page']=$gp['page'];
        $data['permission']=$this->permission;
        $this->load->view('defaults/customers_list',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 客户预存款列表
     */
    public function khdepositlist(){
        $gp=gp();
        if($gp['keyword']){
            $keyword=array(
                'email'=>$gp['keyword'],
                'name'=>$gp['keyword'],
            );
        }
        $data['depositrecordlist']=$this->users_model->depositrecordlist($keyword);
        $this->load->view('defaults/customers_deposit_list',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 导出SF数据模板
     * @param string $type
     */
    public function ExportCustomer(){
        $gp=gp();
        $keyword=array();
        if($gp['keyword']) {
            $keyword = array(
                'name' => $gp['keyword'],
                'email' => $gp['keyword'],
                'tel' => $gp['keyword'],
            );
        }
        if($gp['type']==''){
            $gp['type']=1;
        }
        switch($gp['ExportType']){
            case 'customer':
                $data = $this->users_model->customerslist($keyword,$gp['type']);
                foreach($data as &$row){
                    $row['CustomerNum__c']=$row['id'];
                    $row['Name']=$row['name'];
                    $row['Parent']='';
                    $row['Brand__c']='';
                    $row['Status__c']='';
                    $row['CSSupport__c']='';
                    $row['MainProducts__c']='';
                    $row['Remark__c']='';
                    $row['Description']='';
                    $row['Owner']='';
                    $row['RecordType']='';
                    $row['Phone']=$row['tel'];
                    $row['NumberOfEmployees']='';
                    $row['Website']='';
                    $row['SalesPlatform__c']='';
                    $row['Last Name']=$row['name'];;
                    $row['First Name']=$row['name'];;
                    $row['Middle Name']=$row['name'];;
                    $row['Suffix']='';
                    $row['Origin']='';
                    $row['Contacting']='';
                    $row['PersonEmail']=$row['email'];
                    $row['Type']='Type';
                    $row['Phone2__pc']=$row['tel'];
                    $row['Facebook__pc']='';
                    $row['QQ__pc']='';
                    $row['Twitter__pc']='';
                    $row['Origin__c']='';
                    $row['NumberOfTechnicians__c']='';
                    $row['NIF_CIF__c']='';
                    $row['RepairableProducts__c']='';
                    $row['PayVAT__c']='';
                    $row['CommencementDate__c']='';
                    $row['Fax__c']='';
                }
                unset($row);
                $arrayList=$this->ExportType($gp['type']);
                break;
            case 'contacts':
                $data = $this->users_model->ContactListAll();
                foreach($data as &$row){
                    $row['Last Name']=$row['fullName'];
                    $row['First Name']=$row['fullName'];
                    $row['Middle Name']=$row['fullName'];
                    $row['Suffix']='';
                    $row['CustomerNum__c']=$row['customers_id'];
                    $row['Title']='';
                    $row['Email']=$row['email'];
                    $row['Phone']=$row['phone'];
                    $row['MobilePhone']='';
                    $row['Phone2__c']='';
                    $row['Type__c']='';
                    $row['Grade__c']='';
                    $row['Experience__c']='';
                    $row['Owner']='';
                    $row['ReportsTo']='';
                    $row['Department']='';
                    $row['Fax']='';
                    $row['Facebook__c']='';
                    $row['Twitter__c']='';
                    $row['QQ__c']='';
                    $row['WeChat__c']='';
                }
                unset($row);
                $arrayList=array(
                    'id'=>'id',
                    'Last Name'=>'Last Name',
                    'First Name'=>'First Name',
                    'Middle Name'=>'Middle Name',
                    'Suffix'=>'Suffix',
                    'CustomerNum__c'=>'CustomerNum__c',
                    'Title'=>'Title',
                    'Email'=>'Email',
                    'Phone'=>'Phone',
                    'MobilePhone'=>'MobilePhone',
                    'Phone2__c'=>'Phone2__c',
                    'Type__c'=>'Type__c',
                    'Grade__c'=>'Grade__c',
                    'Experience__c'=>'Experience__c',
                    'Owner'=>'Owner',
                    'ReportsTo'=>'ReportsTo',
                    'Department'=>'Department',
                    'Fax'=>'Fax',
                    'Facebook__c'=>'Facebook__c',
                    'Twitter__c'=>'Twitter__c',
                    'QQ__c'=>'QQ__c',
                    'WeChat__c'=>'WeChat__c',
                );
                break;
            default:
                echo 'shit';
        }
        $typeName='';
        switch($gp['type']){
            case '1':
                $typeName='Merchant';
                break;
            case '2':
                $typeName='Brand';
                break;
            case '3':
                $typeName='Person';
                break;
            case '4':
                $typeName='Repair Shop';
                break;
            default:
        }
        if($gp['ExportType']=='contacts'){
            $typeName='';
        }
        excel_output($gp['ExportType'].$typeName,$arrayList,$data);
    }

    /**
     * 各客户类型导出列
     * @param string $type
     */
    public function ExportType($type=''){
        $arrayList=array();
        switch($type){
            case '1':
                $arrayList=array(
                    'id'=>'id',
                    'CustomerNum__c'=>'CustomerNum__c',
                    'Name'=>'Name',
                    'Parent'=>'Parent',
                    'MainProducts__c'=>'MainProducts__c',
                    'CSSupport__c'=>'CSSupport__c',
                    'SalesPlatform__c'=>'SalesPlatform__c',
                    'Description'=>'Description',
                    'Remark__c'=>'Remark__c',
                    'Owner'=>'Owner',
                    'RecordType'=>'RecordType',
                    'CurrencyIsoCode'=>'CurrencyIsoCode',
                    'Phone'=>'Phone',
                    'NumberOfEmployees'=>'NumberOfEmployees',
                    'Status__c'=>'Status__c',
                    'Website'=>'Website',
                );
                break;
            case '2':
                $arrayList=array(
                    'id'=>'id',
                    'CustomerNum__c'=>'CustomerNum__c',
                    'Name'=>'Name',
                    'Parent'=>'Parent',
                    'Brand__c'=>'Brand__c',
                    'Status__c'=>'Status__c',
                    'CSSupport__c'=>'CSSupport__c',
                    'MainProducts__c'=>'MainProducts__c',
                    'Remark__c'=>'Remark__c',
                    'Description'=>'Description',
                    'Owner'=>'Owner',
                    'RecordType'=>'RecordType',
                    'Phone'=>'Phone',
                    'NumberOfEmployees'=>'NumberOfEmployees',
                    'Website'=>'Website',
                );
                break;
            case '3':
                $arrayList=array(
                    'id'=>'id',
                    'CustomerNum__c'=>'CustomerNum__c',
                    'Last Name'=>'Last Name',
                    'First Name'=>'First Name',
                    'Middle Name'=>'Middle Name',
                    'Suffix'=>'Suffix',
                    'Origin'=>'Origin',
                    'Description'=>'Description',
                    'Contacting'=>'Contacting',
                    'PersonEmail'=>'PersonEmail',
                    'SalesPlatform__c'=>'SalesPlatform__c',
                    'Owner'=>'Owner',
                    'RecordType'=>'RecordType',
                    'CurrencyIsoCode'=>'CurrencyIsoCode',
                    'Type'=>'Type',
                    'Phone'=>'Phone',
                    'Phone2__pc'=>'Phone2__pc',
                    'Facebook__pc'=>'Facebook__pc',
                    'QQ__pc'=>'QQ__pc',
                    'Twitter__pc'=>'Twitter__pc',
                    'Remark__c'=>'Remark__c',
                );
                break;
            case '4':
                $arrayList=array(
                    'id'=>'id',
                    'CustomerNum__c'=>'CustomerNum__c',
                    'Name'=>'Name',
                    'Description'=>'Description',
                    'CurrencyIsoCode'=>'CurrencyIsoCode',
                    'Origin__c'=>'Origin__c',
                    'Status__c'=>'Status__c',
                    'NumberOfTechnicians__c'=>'NumberOfTechnicians__c',
                    'NIF_CIF__c'=>'NIF_CIF__c',
                    'Owner'=>'Owner',
                    'Parent'=>'Parent',
                    'Phone'=>'Phone',
                    'NumberOfEmployees'=>'NumberOfEmployees',
                    'Website'=>'Website',
                    'RepairableProducts__c'=>'RepairableProducts__c',
                    'PayVAT__c'=>'PayVAT__c',
                    'CommencementDate__c'=>'CommencementDate__c',
                    'Fax__c'=>'Fax__c',
                    'Remark__c'=>'Remark__c',
                );
                break;
            default:
        }
        return $arrayList;
    }
    /**
     * 审核客户存款
     * @param $id
     * @param $email
     * @param $money
     * @param $status
     */
    public function auditdeposit($id,$email,$name,$money,$status){
        $email=base64_decode($email);
        $up=$this->users_model->auditdeposit($id,$status);
        if($status==1) {
            if ($up) {
                $em = $this->users_model->verificationemail($email);
                if ($em) {
                    $this->users_model->upddeposit($email, $money);
                } else {
                    $data = array(
                        'email' => $email,
                        'money' => $money,
                        'name'=> $name,
                    );
                    $this->users_model->adddeposit($data);
                }
            }
        }
        $this->depositrecordlist();
    }
    public function td(){
        $this->users_model->td();
    }
    /**
     * 存款记录列表
     */
    public function depositrecordlist(){
        $gp=gp();
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str="?keyword=".$gp['keyword']."&moneyType=".$gp['moneyType']."&country_code=".$gp['country_code']."&currency=".$gp['currency'];
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('users/member/depositrecordlist'.$str);
        $config['total_rows'] = $this->users_model->CountDepositRecord(trim($gp['keyword']),$gp['moneyType'],$gp['country_code'],$gp['currency']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageShow']= $this->pagination->create_links();
        //分页结束
        //资金记录数据列表
        $data['depositrecordlist']=$this->users_model->depositlistrecord(trim($gp['keyword']),'',$gp['moneyType'],$gp['country_code'],$gp['currency'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        //客户列表
        $data['customersList']=$this->users_model->GetCustomersSelect();
        //站点列表
        $data['pointList']=$this->users_model->GetPoint();
        //资金详情
        $data['capitalDetails']=$this->capitalDetails($gp['keyword'],$gp['moneyType'],$gp['moneyType'],$gp['currency']);
        //记录搜索数据
        $data['searchData']=array(
            'keyword'=>$gp['keyword'],
            'moneyType'=>$gp['moneyType'],
            'country_code'=>$gp['country_code'],
            'currency'=>$gp['currency']
        );
        $data['str']=$str;
        $this->load->view('defaults/customers_deposit_record_list',$data);
        $this->load->view('defaults/common/footer');
    }

    public function paymentrecord()
    {
        $gp = gp();
        $gp['page'] ? $gp['page'] = $gp['page'] : $gp['page'] = 1;
        $str = "?keyword=" . $gp['keyword'] . "&moneyType=" . $gp['moneyType'];
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('users/member/paymentrecord' . $str);
        $config['total_rows'] = $this->users_model->CountPaymentRecord(trim($gp['keyword']), $gp['moneyType']);
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageShow'] = $this->pagination->create_links();
        //分页结束
        //资金记录数据列表
        $data['depositrecordlist'] = $this->users_model->paymentrecord(trim($gp['keyword']), '', $gp['moneyType'], $config['per_page'], ($gp['page'] - 1) * $config['per_page']);

        //记录搜索数据
        $data['searchData'] = array(
            'keyword' => $gp['keyword'],
            'moneyType' => $gp['moneyType']
        );
        $this->load->view('defaults/paymentrecord', $data);
        $this->load->view('defaults/common/footer');
    }




    /**
     * 添加存款(扣款，后期新增需求)记录
     */
    public function AddDepositRecord(){
        $gp=gp();
        $accountArray=array('parisa','lyb','Trista','prezwang','dhhtgaogao','vivian','吴丹丹','Monty','guoyang','homguang','林平平','chuyilin','邱远琴','Romy','sony');
        if(in_array($this->users['account'],$accountArray)) {
            $data = array(
                'customers_id' => $gp['customers_id'],
                'transactionId' => $gp['transactionId'],
                'currency' => $gp['customers_currency'],
                'payment_type'=>$gp['payment_type'],
                'bank_subject'=>$gp['bank_subject'],
                'add_name' => $this->users['name'],
                'time' => time()
            );
            //判断是否需要货币转换
            if (strcasecmp(trim($gp['currency']), trim($gp['customers_currency']))) {
                //对人民币汇率
                $rateArray = array('USD' => 6.7977, 'EUR' => 7.6235, 'GBP' => 8.6523, 'CNY' => 1 ,'RUB'=>0.1133);
                //汇损
                $hs = 1;
                $money = currency_service($gp['currency'], $gp['customers_currency'], $gp['money']);
                //接口出错采用固有汇率
                if(!$money){
                    $currency_code = strtoupper(trim($gp['currency']));
                    $money=$gp['money']*$rateArray[$currency_code];
                }
            } else {
                $hs = 1;
                $money=$gp['money'];
            }
            //判断是否是扣款
            if ($gp['orderId'] && $gp['country_code']) {
                $data['orderId'] = $gp['orderId'];
                $data['country_code'] = $gp['country_code'];
                $data['money'] = -$money;
                //查询客户信息
                $clineInfo = $this->users_model->GetClineInfo($gp['customers_id']);
                //判断余额是否透支完毕
                $facilityExtent = $clineInfo['facilityExtent'] + ($clineInfo['Balances'] - $money);
                if ($facilityExtent >= 0) {
                    //添加存款记录并返回ID号
                    $id = $this->users_model->AddDepositRecord($data);
                    //更新余额
                    $this->users_model->UpdateBalances_new($gp['customers_id'], $data['money']);
                } else {
                    js_goto('','客户余额不足',1);
                }
            } else {
                $data['money'] = $money / $hs / $hs;
                //添加存款记录并返回ID号
                $id = $this->users_model->AddDepositRecord($data);
                //更新余额
                $this->users_model->UpdateBalances_new($gp['customers_id'], $data['money']);
            }
            /*//查询客户当前余额
            $balances=$this->users_model->GetCustomersBalances($gp['customers_id']);
            //生成推送给SF数据
            $data=array(
                'OMSID__c'=>$id,
                'OMSOrderID__c'=>'',
                'Amount__c'=>$gp['money'],
                'Balance__c'=>$balances,
                'CustomerNum__c'=>$gp['customers_id'],
                'CurrencyIsoCode'=>$gp['currency'],
                'Type__c'=>'Deposit'
            );
            //推送数据至SF
            //$sfResult=$this->SalesForce_model->oms_to_sf006($data);
            //资金记录数据列表*/
            redirect(blang_url('users/member/depositrecordlist'));
        }else{
            js_goto('','你没有权限',1);
        }
    }
    /**
     * 导出资金数据
     */
    public function ExportFundsData(){
        $gp=gp();
        $data=$this->users_model->depositlistrecord(trim($gp['keyword']),'',$gp['moneyType'],$gp['country_code']);
        foreach($data as &$row){
            $row['time']=date('Y-m-d H:i:s',$row['time']);
        }
        unset($row);
        $fieldData=array(
            'country_code'=>'站点',
            'transactionId'=>'交易信息',
            'name'=>'客户',
            'money'=>'变更额度',
            'currency'=>'币种',
            'time'=>'变更时间',
            'orderId'=>'变更单号',
        );
        excel_output('fundsData',$fieldData,$data);
    }
    /**
     *新增联系人
     */
    public function AddContact(){
        $gp=gp();
        $this->users_model->AddContact($gp);
        redirect();
    }

    /**
     * tomRepair 账号列表
     */
    public function TrAccountList(){
        $gp=gp();
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $str="?keyword=".$gp['keyword'];
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('users/member/TrAccountList'.$str);
        $config['total_rows'] = $this->users_model->CountTrAccount($gp['keyword']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 15;
        $this->pagination->initialize($config);
        $data['pageShow']= $this->pagination->create_links();
        //分页结束
        $data['accountList']=$this->account_model->AccountList($gp['keyword'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        if($gp['error_msg']) {
            if($gp['error_msg']=='OK') {
                $data['msg'] = '信息成功推送至TomRepair<' . $gp['error_msg'] . '>';
            }else{
                $data['msg'] = '信息推送失败<' . $gp['error_msg'] . '>';
            }
        }
        $this->load->view('defaults/tomRepair/Account_list',$data);
    }

    /**
     * 设置账号信息
     */
    public function SetAccount(){
        $gp=gp();
        $branchStr='';
        $permissionStr='';
        $branch=array();
        //重构店铺数组 以，连接字符串入库
        if($gp['branch']) {
            foreach ($gp['branch'] as $key => $val) {
                $branchExp = explode('_/', $val);
                $branch[] = $branchExp[0];
            }
            $branchStr = implode(',', $branch);
        }
        //重构权限数组 以，连接字符串入库
        if($gp['permission']){
            $permissionStr = implode(',', $gp['permission']);
        }
        //更新项
        $data=array(
            'role'=>$gp['role'],
            'branch'=>$branchStr,
            'pay_shop_id'=>$gp['pay_shop_id'],
            'permission'=>$permissionStr
        );
        $result=$this->account_model->UpdateAccount($gp['id'],$data);
        //更新成功之后将数据推送至TomRepair
        if($result)
        {
            $data=array(
                'tr_id'=>$gp['tr_id'],
                'branch'=>$branch,
                'permission'=>$gp['permission'],
                'customer_num'=>$gp['pay_shop_id'],
                'role'=>$gp['role'],
            );
            $to=$this->OMS_to_TomRepair($data);
            if($to['error_code'] != '100'){
                redirect(blang_url('users/member/TrAccountList?error_msg='.urlencode($to['error_msg'])));
            }else{
                redirect(blang_url('users/member/TrAccountList?error_msg='.urlencode($to['error_msg'])));
            }
        }
    }

    /**
     * 推送数据至TomRepair
     * @param $data
     * @return mixed
     */
    public function OMS_to_TomRepair($data){
        $permission=array(
            'dash_place_orders'=>'0',
            'dash_tickets'=>'0',
            'dash_messages'=>'0',
            'dash_orders'=>'0',
            'dash_balance'=>'0',
            'dash_products'=>'0',
            'dash_batch_orders'=>'0'
        );
        foreach($data['permission'] as $key=>$val){
            switch($val){
                case '1':
                    $permission['dash_place_orders']='1';
                    break;
                case '2':
                    $permission['dash_tickets']='1';
                    break;
                case '3':
                    $permission['dash_messages']='1';
                    break;
                case '4':
                    $permission['dash_orders']='1';
                    break;
                case '5':
                    $permission['dash_balance']='1';
                    break;
                case '6':
                    $permission['dash_products']='1';
                    break;
                case '7':
                    $permission['dash_batch_orders']='1';
                    break;
                default:
                    $permission=array(
                        'dash_place_orders'=>'0',
                        'dash_tickets'=>'0',
                        'dash_messages'=>'0',
                        'dash_orders'=>'0',
                        'dash_balance'=>'0',
                        'dash_products'=>'0',
                        'dash_batch_orders'=>'0',
                    );
                    break;
            }
        }
        $baseUrl= base_url();
        if($baseUrl=='http://oms.tomrepair.es/'){
            $url = "http://www.tomrepair.cn/api/index.php/updatePermissionAndShop";
        }else{
            $url = "http://test.dhhtgroup.com:8099/api/index.php/updatePermissionAndShop";
        }
        $data_to_post = array();
        $data_to_post['user'] = 'api@tomrepair.es';
        $data_to_post['token'] = '78de933bd0fbacf02ef2de1116e3338f1c627b07';
        $data_to_post['user_id'] = $data['tr_id'];
        $data_to_post['customer_num'] = $data['customer_num'];
        $data_to_post['websites'] = $data['branch'];
        $data_to_post['permissions'] = $permission;
        $data_to_post['user_type'] = $data['role'];
        $result=TomRepairCurlPost($url,$data_to_post);
        return $result;
    }

    /**
     * 添加虚拟仓库
     */
    public function AddWarehouse(){
        $gp=gp();
        $str=$gp['str'];
        $page=$gp['page'];
        unset($gp['page']);
        unset($gp['str']);
        foreach($gp['site_id'] as $key=>$val){
            $data=array(
                'site_id'=>$val,
                'warehouse_code'=>$gp['warehouse_code'][$key],
                'brand_client_id'=>$gp['brand_client_id'],
                'warranty_interior'=>$gp['warranty_interior'][$key],
                'warranty_external'=>$gp['warranty_external'][$key],
                'sell'=>$gp['sell'][$key]
            );
            $query=$this->users_model->GetVirtualWarehouseCode($val,$gp['brand_client_id']);
            if($query) {
                $uData=array(
                    'warehouse_code'=>$gp['warehouse_code'][$key],
                    'warranty_interior'=>$gp['warranty_interior'][$key],
                    'warranty_external'=>$gp['warranty_external'][$key],
                    'sell'=>$gp['sell'][$key]
                );
                $this->users_model->UpdateWarehouse($val,$gp['brand_client_id'],$uData);
            }else{
                $this->users_model->AddWarehouse($data);
            }
        }
        redirect(blang_url('users/member/ConsumerList'.$str));
    }

    /**
     *设置核销处理方式
     */
    public function SetChargeOff(){
        $gp=gp();
        $str=$gp['str'];
        unset($gp['str']);
        $data=array(
            'chargeOff'=>$gp['chargeOff']
        );
        $this->common_model->update('mt_customers',$data,array('id'=>$gp['customers_id']));
        redirect(blang_url('users/member/ConsumerList'.$str));
    }
    /**
     * 更新客户信息
     */
    public function UpdateClientInfo(){
        $gp=gp();
        $id=$gp['id'];
        $page=$gp['str'];
        unset($gp['str']);
        unset($gp['page']);
        unset($gp['id']);
        if($gp['manager']) {
            $manager = explode('_', $gp['manager']);
            $gp['manager_id']=$manager[0];
            $gp['manager_name']=$manager[1];
        }else{
            $gp['manager_id']=0;
            $gp['manager_name']='';
        }
        unset($gp['manager']);
        $data=$gp;
        $this->users_model->updatecustomerslist($id,$data);
        redirect(blang_url('users/member/ConsumerList'.$page));
    }
    /**
     * 修改会员状态
     * @param string $id
     * @param string $enable
     * @param string $page
     */
    function set_active($id='',$enable='',$page='') {
        $page = max(intval($page),1);
        $enable?$enable=0:$enable=1;
        $this->common_model->update($this->t_user,array('active'=>$enable),array('id'=>intval($id)));
        redirect(blang_url('users/member/?page='.$page));
    }

    /**
     * 修改会员外网权限
     * @param string $id
     * @param string $enable
     * @param string $page
     */
    function set_isopen($id='',$enable='',$page='') {
        $page = max(intval($page),1);
        $enable?$enable=0:$enable=1;
        $this->common_model->update($this->t_user,array('is_open'=>$enable),array('id'=>intval($id)));
        redirect(blang_url('users/member/?page='.$page));
    }

    /**
     * 修改用户基本资料和权限租
     */
    function ajaxEditUser()
    {
        $formData = gp();
        $uid = $formData['uid'];
        $email = $formData['email'];
        $realname = $formData['uname'];
        $deparment = $formData['dept'];//部门
        $pwd = trim($formData['pwd']);
        $role_id = rtrim($formData['rids'], ',');
        $franchisees_id = $formData['franchisees_id'];
        $data = array(
            'email' => $email,
            'name' => $realname,//真实姓名
            'position' => $deparment,//部门
            'role_id' => $role_id,
            'franchisees_id'=>$franchisees_id
        );
        if (!empty($pwd)) {
            $data['password'] = md5($pwd);
        }
        $res = $this->users_model->updateUserInfo(intval($uid), $data);
        echo($res);
        exit;

    }
    /**
     * 角色列表
     */
    function roleList(){
        $roleList=$this->users_model->GetRole();
        $language=$this->uri->segment(1);
        $data['roleInfo'] = array();
        foreach($roleList as &$row){
            if (in_array($row['id'], explode(',', $this->users['role_id']))) {
                $data['roleInfo']['name'] .= $row['name_ch'].',';
                $data['roleInfo']['name_en'] .= $row['name_en'].',';
            }
            switch($language){
                case 'sc':
                    $row['name']=$row['name_ch'];
                    break;
                case 'english':
                    $row['name']=$row['name_en'];
                    break;
                default:
                    $row['name']=$row['name_en'];
                    break;
            }
        }
        unset($row);
        $data['roleData']=$roleList;
        $data['roleInfo']['name'] = trim($data['roleInfo']['name'], ',');
        $data['roleInfo']['name_en'] = trim($data['roleInfo']['name_en'], ',');
        //视图以及样式
        $this->load->view('defaults/users_role', $data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 新增角色
     */
    function AddRole(){
        $gp=gp();
        $data=array(
            'name_en'=>$gp['name_en'],
            'name_ch'=>$gp['name_ch']
        );
        $this->users_model->AddRole($data);
        redirect(blang_url('users/member/roleList'));
    }

    /**
     * 更新角色
     */
    function UpdateRole(){
        $gp=gp();
        $data=array(
            'name_ch'=>$gp['name_ch'],
            'name_en'=>$gp['name_en']
        );
        $this->users_model->UpdateRole($gp['id'],$data);
        redirect(blang_url('users/member/roleList'));
    }

    /**
     * 权限设置
     */
    function SetPermission(){
        //视图以及样式
        $gp=gp();
        if($gp['update']){
            $this->users_model->setRolePermission($gp['id'], $gp['ids']);
            redirect(blang_url('users/member/roleList'));
        }else {
            $tree = $this->users_model->getRolePermissionTree(null);
            $roleInfo=$this->users_model->GetRoleInfo($gp['id']);
            $roleInfo['permission']=json_decode($roleInfo['permission'],true);
            $data['roleInfo']=$roleInfo;
            $data['tree']=$tree;
            $this->load->view('defaults/permission_list', $data);
            $this->load->view('defaults/common/footer');
        }
    }

    /**
     * 获取权限数据(数据展示可以实现无限级分类，前端一直困扰如何实现，忘后续开发人员可以完善)
     * @param int $parent_id
     * @return array
     */
    // public function GetPermissionData($parent_id=0){
    //     $resultArray=array();
    //     $permissionList=$this->users_model->GetPermissionData($parent_id);
    //     if($permissionList){
    //         foreach($permissionList as $row){
    //             $row['children']=$this->GetPermissionData($row['id']);
    //             $resultArray[]=$row;
    //         }
    //     }
    //     return $resultArray;
    // }

    /**
     * 张伟 转换role表字段数据------------临时功能
     */
    public function tempChange() {
        // $result = $this->db->select('id,permission')->from('mt_role')->get()->result_array();
        // foreach ($result as $role) {
        //     $permissions = json_decode($role['permission'], true);
        //     $data1 = array();
        //     $data2 = array();
        //     foreach ($permissions as $key => $enable) {
        //         $re = $this->db->select('id')->where('menu_key', $key)->from('mt_permission')->get()->row_array();
        //         if ($re['id']) {
        //             $enable ? array_push($data1, $re['id']) : array_push($data2, $re['id']);
        //             condition;
        //         }
        //         $re = $this->db->select('id')->where("CONCAT_WS('_', class_name, function_name) like '%{$key}'")->from('mt_permission')->get()->row_array();
        //         if ($re['id']) {
        //             $enable ? array_push($data1, $re['id']) : array_push($data2, $re['id']);
        //             condition;
        //         }
        //     }
        //     if(!empty($data1)){
        //         $this->db->where('id', $role['id'])->update('mt_role', array(
        //             'permission' => json_encode($data1)
        //         )); 
        //     }
        //     // print_r($data1);
        //     // print_r($data2);
        // }
header('content-type: text/html; charset=utf-8;');
        if ($this->uri->segment(1) != 'english') {
            return 0;
        }
        $menus = config_menus();
        $base = ['name','title','url','isshow'];
        foreach ($menus as $v1) {
            if(substr($v1['url'], -1) == '/'){
                $keys1 = array_keys($v1);
                $keys1 = array_filter($keys1, function($v) use ($base){
                    return !in_array($v, $base);
                });
                $class_name1 = trim($v1['url'], '/');
                foreach ($keys1 as $function_name1) {
                    if (is_array($v1[$function_name1])) {
                        $v2 = $v1[$function_name1];
                        if(substr($v2['url'], -1) == '/'){
                            $keys2 = array_keys($v2);
                            $keys2 = array_filter($keys2, function($v) use ($base){
                                return !in_array($v, $base);
                            });
                            $class_name2 = trim($v2['url'], '/');
                            foreach ($keys2 as $function_name2) {
                                if (is_array($v2[$function_name2])) {
                                    $v3 = $v2[$function_name2];
                                    if(substr($v3['url'], -1) == '/'){
                                        $keys3 = array_keys($v3);
                                        $keys3 = array_filter($keys3, function($v) use ($base){
                                            return !in_array($v, $base);
                                        });
                                        $class_name3 = trim($v3['url'], '/');
                                        foreach ($keys3 as $function_name3) {
                                            if (is_array($v3[$function_name3])) {

                                            }
                                            if($function_name3){
                                                echo $class_name3.'/'.$function_name3.'=>'.$v3[$function_name3]['name'].'<br>';
                                                $this->db
                                                    ->where('class_name', $class_name3)
                                                    ->where('function_name', $function_name3)
                                                    ->update('mt_permission',['description_en' => $v3[$function_name3]['name']]);
                                            }
                                        }
                                    }else{
                                        $arr = explode('/', $v3['url']);
                                        $function_name3 = array_pop($arr);
                                        $class_name3= implode('/', $arr);
                                        if($function_name3){
                                            echo $class_name3.'/'.$function_name3.'=>'.$v3['name'].'<br>';
                                            $this->db
                                                ->where('class_name', $class_name3)
                                                ->where('function_name', $function_name3)
                                                ->update('mt_permission',['description_en' => $v3['name']]);
                                        }
                                    }
                                }
                                if($function_name2){
                                    echo $class_name2.'/'.$function_name2.'=>'.$v2[$function_name2]['name'].'<br>';
                                    $this->db
                                        ->where('class_name', $class_name2)
                                        ->where('function_name', $function_name2)
                                        ->update('mt_permission',['description_en' => $v2[$function_name2]['name']]);
                                }
                            }
                        }else{
                            $arr = explode('/', $v2['url']);
                            $function_name2 = array_pop($arr);
                            $class_name2= implode('/', $arr);
                            if($function_name2){
                                echo $class_name2.'/'.$function_name2.'=>'.$v2['name'].'<br>';
                                $this->db
                                    ->where('class_name', $class_name2)
                                    ->where('function_name', $function_name2)
                                    ->update('mt_permission',['description_en' => $v2['name']]);
                            }
                        }

                    }
                    if($function_name1){
                        echo $class_name1.'/'.$function_name1.'=>'.$v1[$function_name1]['name'].'<br>';
                        $this->db
                            ->where('class_name', $class_name1)
                            ->where('function_name', $function_name1)
                            ->update('mt_permission',['description_en' => $v1[$function_name1]['name']]);
                    }
                }
            }else{
                $arr = explode('/', $v1['url']);
                $function_name1 = array_pop($arr);
                $class_name1 = implode('/', $arr);
                if($function_name1){
                    echo $class_name1.'/'.$function_name1.'=>'.$v1['name'].'<br>';
                    $this->db
                        ->where('class_name', $class_name1)
                        ->where('function_name', $function_name1)
                        ->update('mt_permission',['description_en' => $v1['name']]);
                }
            }
            
        }
        
        echo '执行完成';
    }


    /**
     * 张伟 获取父权限id串
     */
    public function getPermissionParentIds() {
        $id = intval($this->input->get('id'));
        $parent_ids = $this->users_model->getPermissionParentIds($id);
        $this->output->set_output('');
        json_output($parent_ids, '成功', true);
    }

    /**
     * 张伟 获取子权限列表
     */
    public function getPermissionChildren() {
        $parent_id = intval($this->input->get('parent_id'));
        $list = $this->users_model->getPermissionChildren($parent_id);
        $this->output->set_output('');
        json_output($list, '成功', true);
    }

    /**
     * 权限维护
     */
    public function PermissionMaintain(){
        //$tree = $this->users_model->getRolePermissionTree($this->users['role_id']);
        $tree = $this->users_model->getRolePermissionTree(null);
        $this->load->view('defaults/permission_maintain', array('tree' => $tree));
        $this->load->view('defaults/common/footer');
    }

    /**
     * 添加权限
     */
    public function AddPermission(){
        $gp=gp();
        $this->users_model->AddPermission($gp);
        redirect(blang_url('users/member/PermissionMaintain#permission-'.$gp['parent_id']));
    }

    /**
     * 编辑权限
     */
    public function UpdatePermission(){
        $gp=gp();
        $this->users_model->UpdatePermission($gp['id'],$gp);
        redirect(blang_url('users/member/PermissionMaintain#permission-'.$gp['id']));
    }

    /**
     * 删除权限
     */
    public function DeletePermission(){
        $this->output->set_output('');
        $id = (int)$this->input->post('id');
        $this->db->trans_begin();
        if (true === $this->users_model->DeletePermission($id) && $this->db->trans_status() === FALSE){
            $this->db->trans_rollback();
            json_output([], '删除失败', false);
        }
        else{
            $this->db->trans_commit();
            json_output([], '删除成功', true);
        }
    }

    /**
     * 资金详情
     * @param string $keyword
     * @param string $type
     * @param string $point
     * @param string $currency
     * @return array
     */
    public function capitalDetails($keyword='',$type='',$point='',$currency=''){
        $data=array();
        //个币种总额
        $total=$this->users_model->capitalDetails($keyword,$type,$point,$currency);
        foreach($total as $t){
            $data['total'][$t['currency']]=$t['moneyTotal'];
        }
        //各币种充值总额
        $addTotal=$this->users_model->capitalDetails($keyword,$type,$point,$currency,'add');
        foreach($addTotal as $a){
            $data['addTotal'][$a['currency']]=$a['moneyTotal'];
        }
        //各币种扣款总额
        $subtractTotal=$this->users_model->capitalDetails($keyword,$type,$point,$currency,'subtract');
        foreach($subtractTotal as $s){
            $data['subtractTotal'][$s['currency']]=$s['moneyTotal'];
        }
        return $data;
    }

    /**
     * 自动同意报价额度列表
     */
    public function AutoAgreeQuota(){
        $pagesize = 15;
        $page = max(1, intval($this->input->get_post('page')));
        //客户
        $customers = $this->db->select('id,name name_ch,name_en')->from('mt_customers')->where('type',1)->order_by('name_en asc,id asc')->get()->result_array();
        //产品类型
        $product_cats = $this->db->select('id,name_ch,name_en')->from('mt_product_category')->where('available',1)->order_by('name_en asc,id asc')->get()->result_array();
        //条件
        $condition = array('caq.is_deleted' => 0);
        $search = array();
        if($this->input->get_post('customer_id') > 0){
            $condition['caq.customer_id'] = intval($this->input->get_post('customer_id'));
            $search['customer_id'] = $condition['caq.customer_id'];
        }
        if($this->input->get_post('product_category_id') > 0){
            $condition['caq.product_category_id'] = intval($this->input->get_post('product_category_id'));
            $search['product_category_id'] = $condition['caq.product_category_id'];
        }

        //列表
        $list = $this->db
            ->select('caq.id,caq.amount,caq.currency_code,caq.create_at,caq.update_at,c.id customer_id,c.name cu_name_ch,c.name_en cu_name_en,pc.name_ch pcat_name_ch,pc.name_en pcat_name_en')
            ->from('mt_customer_agree_quota caq')
            ->join('mt_customers c','caq.customer_id=c.id','left')
            ->join('mt_product_category pc','caq.product_category_id=pc.id','left')
            ->where($condition)
            ->order_by('caq.id desc')
            ->limit($pagesize, ($page - 1)*$pagesize)
            ->get()
            ->result_array();
        foreach ($list as $k => &$v) {
            $v['create_at'] = date('Y-m-d H:i:s', $v['create_at']);
            $v['update_at'] = $v['update_at'] > 0 ? date('Y-m-d H:i:s', $v['update_at']) : '';
        }
        //统计数量
        $sql = $this->db->last_query();//echo $sql;
        $sql = substr($sql, 0, stripos($sql, 'ORDER BY'));
        $sql = preg_replace('/(SELECT).*?(FROM.*)/is', '$1 count(*) `rows` $2', $sql);
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $total_rows = (int)$row['rows']; //总数量
        $pagecount = ceil($total_rows / $pagesize); //总页数

        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('users/member/AutoAgreeQuota?'.$search);
        $config['total_rows'] = $total_rows;
        $config['per_page'] = $pagesize;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $this->pagination->initialize($config);


        $this->load->view('defaults/member_auto_agree_quota', array(
            'customers' => $customers,
            'product_cats' => $product_cats,
            'list' => $list,
            'search' => $search,
            'show_pages' => $this->pagination->create_links(),
            'show_params' => "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$pagecount}页"
        ));
        $this->load->view('defaults/common/footer');
    }

    /**
     * 自动同意报价额度设置
     */
    public function AutoAgreeQuotaAdd(){
        if (!empty($_POST)) {
            $post = $this->input->post();
            $customer_id = intval($post['customer_id']);
            $amount = floatval($post['amount']);
            $currency_code = 'USD';
            if ($customer_id < 1 || $amount < 0.01 || !$currency_code) {
                show_error('参数错误');
            }
            $post['product_category_ids'] = explode(',', trim($post['product_category_ids'], ','));
            $data = array();
            foreach ($post['product_category_ids'] as $catid) {
                $old = $this->db
                    ->where("customer_id = {$customer_id} and product_category_id = {$catid}")
                    ->from('mt_customer_agree_quota')
                    ->get()->row_array();
                if ($old) {
                    $this->db
                        ->where('id', $old['id'])
                        ->update('mt_customer_agree_quota', array(
                            'amount' => $amount,
                            'currency_code' => $currency_code,
                            'is_deleted'=>0,
                            'delete_at'=>0,
                            'delete_by'=>0
                        ));
                    continue;
                }
                array_push($data, array(
                    'customer_id' => $customer_id,
                    'product_category_id' => $catid,
                    'amount' => $amount,
                    'currency_code' => $currency_code,
                    'create_at' => time(),
                    'create_by' => $this->users['id']
                ));
            }
            $this->db->insert_batch('mt_customer_agree_quota', $data);
            redirect(blang_url('users/member/AutoAgreeQuota'));
        }else{
            //客户
            $customers = $this->db->select('id,name name_ch,name_en')->from('mt_customers')->where('type',1)->order_by('name_en asc,id asc')->get()->result_array();
            $this->output->set_output('');
            $this->load->view('defaults/member_auto_agree_quota_add', array(
                'customers' => $customers,
            ));
        }
    }

    /**
     * 自动同意报价额度编辑
     */
    public function AutoAgreeQuotaEdit(){
        $fields = $this->db->list_fields('mt_customer_agree_quota');
        $data = array();
        foreach ($fields as $field) {
            if ($this->input->post($field)) {
                $data[$field] = $this->input->post($field);
            }
        }
        $id = intval($data['id']);
        unset($data['id']);
        if($data['amount'] < 0.01){
            json_output([], '额度设置错误', false);
        }
        $data['update_at'] = time();
        $data['update_by'] = $this->users['id'];
        $re = $this->db
            ->where('id', $id)
            ->update('mt_customer_agree_quota', $data);
        $this->output->set_output('');
        json_output([], $re?'修改成功':'修改失败', $re);
    }

    /**
     * 自动同意报价额度删除
     */
    public function AutoAgreeQuotaDel(){
        $re = $this->db
            ->where('id', intval($this->input->get('id')))
            ->update('mt_customer_agree_quota', array(
                'is_deleted'=>1,
                'delete_at'=>time(),
                'delete_by'=>$this->users['id']
            ));
        // $this->output->set_output('');
        // json_output([], $re?'删除成功':'删除失败', $re);
        redirect(blang_url('users/member/AutoAgreeQuota'));
    }

    /**
     * 获取产品类型
     */
    public function AutoAgreeQuotaPCats(){
        $this->output->set_output('');
        $customer_id = intval($this->input->post('customer_id'));
        if (!$customer_id) {
            json_output([], '请指定客户id',false);
        }
        //产品类型
        $sql = 'SELECT
        `id`, `name_ch`, `name_en`
        FROM (`mt_product_category`)
        WHERE
            `available`=1
            AND
            `id` NOT IN (SELECT `product_category_id` FROM `mt_customer_agree_quota` WHERE `customer_id`=%d AND is_deleted=0)
        ORDER BY `name_en` ASC,`id` ASC';
        $sql = sprintf($sql, $customer_id);
        $product_cats = $this->db->query($sql)->result_array();
        json_output($product_cats, '成功',true);
    }
}
